<template>
    <div>
        <el-main>
            <div class="box">
                <div class="top">
                    <el-form :inline="true" v-model="queryForm" class="demo-form-inline" style="float: left"
                        size="medium">
                        <!-- <el-form-item label="监测时间(年-月)：">
                            <el-date-picker v-model="queryForm.diaochariqi" type="month" placeholder="选择月" format="yyyy"
                                value-format="yyyy" style="width: 160px" />
                        </el-form-item> -->
                        <el-form-item label="动物类型：">
                            <el-select v-model="queryForm.category" placeholder="请选择">
                                <el-option label="全部" value="">
                                </el-option>
                                <el-option v-for="item in list2" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="中文名：">
                            <el-input v-model="queryForm.name" placeholder="中文名" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="fetchData(queryForm)">查询</el-button>
                        </el-form-item>
                        <el-button @click="visible = true">高级搜索</el-button>
                    </el-form>
                    <div style="
              float: right;
              margin-right: 60px;
              display: flex;
              align-items: center;
            ">
                        <el-button type="primary" size="medium" @click="handleAddPlant">添加</el-button>
                        <!-- <el-button type="danger" style="margin-right: 10px" :disabled="delIds.length === 0"
                            @click="batchDelete">批量删除</el-button> -->
                        <el-button type="success" @click="dialogVisible = true">Excel批量导入</el-button>

                        <el-dialog :visible.sync="dialogVisible" title="动物调查数据批量导入" top="5vh" class="excel-dialo"
                            width="">
                            <div>
                                <div style="margin-bottom: 10px;">
                                    <el-button type="primary" @click="openExcel" size="medium">从Excel导入</el-button>
                                    <input ref="exceluploadinput" type="file" accept=".xlsx, .xls"
                                        style="display: none;" @change="handleFileUpload" />
                                </div>
                                <el-table :data="tableData" border style="width: 100%" height="400" size="medium"
                                    :max-height="tableheight">
                                    <!-- <el-table-column prop="id" label="序号" width="60px" /> -->
                                    <el-table-column prop="wzm" label="中文名" show-overflow-tooltip />

                                    <el-table-column prop="ldm" label="学名" show-overflow-tooltip />
                                    <el-table-column prop="ldmfull" label="拉丁名" show-overflow-tooltip />
                                    <el-table-column prop="shitishuliang" label="实体数量" width="100"
                                        show-overflow-tooltip />
                                    <el-table-column prop="henjishuliang" label="痕迹种类及数量" width="100"
                                        show-overflow-tooltip />
                                    <el-table-column prop="jd" label="经度" width="100" show-overflow-tooltip />
                                    <el-table-column prop="wd" label="纬度" width="100" show-overflow-tooltip />
                                    <el-table-column prop="hb" label="海拔" width="100" show-overflow-tooltip />
                                    <el-table-column prop="podu" label="坡度" width="120" show-overflow-tooltip />
                                    <el-table-column prop="powei" label="坡位" width="120" show-overflow-tooltip />
                                    <el-table-column prop="poxiang" label="坡向" width="120" show-overflow-tooltip />
                                    <el-table-column prop="qixi" label="栖息地类型" width="120" show-overflow-tooltip />
                                    <el-table-column prop="diaochariqi" label="调查时间" width="100" :formatter="formatter"
                                        show-overflow-tooltip />
                                    <el-table-column prop="qixiganrao" label="栖息地干扰" width="120"
                                        show-overflow-tooltip />
                                    <el-table-column prop="protectlevel" label="保护等级" width="120"
                                        show-overflow-tooltip />
                                    <el-table-column prop="location" label="发现地址" width="120" show-overflow-tooltip />
                                    <el-table-column prop="mengshi" label="盟市" width="120" show-overflow-tooltip />
                                    <el-table-column prop="qixian" label="旗县(区)" width="120" show-overflow-tooltip />
                                    <el-table-column prop="source" label="数据来源" width="120" show-overflow-tooltip />
                                    <el-table-column prop="guance" label="观测者" width="100" show-overflow-tooltip />
                                    <el-table-column prop="zpbh" label="照片编号" width="100" show-overflow-tooltip />
                                    <el-table-column prop="sjzpbh" label="生境照片编号" width="100" show-overflow-tooltip />
                                    <el-table-column prop="tezhengmiaoshu" label="特征描述" width="100"
                                        show-overflow-tooltip />
                                    <el-table-column prop="fenbuduodumiaoshu" label="分布多度描述" width="100"
                                        show-overflow-tooltip />
                                    <el-table-column prop="category1" label="动物类型" width="100" :formatter="category"
                                        show-overflow-tooltip />
                                </el-table>
                            </div>
                            <template slot="footer">
                                <el-link type="primary" :underline="false" :href="excelurl">点击下载示例数据</el-link>
                                <span>
                                    <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
                                    <el-button type="primary" @click="handsubmit" size="medium">导 入</el-button>
                                </span>
                            </template>
                        </el-dialog>
                    </div>
                </div>

                <div class="center">
                    <el-table :data="paginatedData" border style="width: 100%" size="medium" :max-height="tableheight">
                        <!-- <el-table-column prop="id" label="序号" width="60px" /> -->
                        <el-table-column prop="wzm" label="中文名" show-overflow-tooltip />

                        <el-table-column prop="ldm" label="学名" show-overflow-tooltip />

                        <el-table-column prop="shitishuliang" label="实体数量" width="100" show-overflow-tooltip />
                        <el-table-column prop="jd" label="经度" width="100" show-overflow-tooltip />
                        <el-table-column prop="wd" label="纬度" width="100" show-overflow-tooltip />
                        <el-table-column prop="hb" label="海拔" width="100" show-overflow-tooltip />
                        <el-table-column prop="mengshi" label="盟市" width="120" show-overflow-tooltip />
                        <el-table-column prop="qixian" label="旗县(区)" width="120" show-overflow-tooltip />
                        <el-table-column prop="guance" label="观测者" width="100" show-overflow-tooltip />
                        <el-table-column prop="diaochariqi" label="调查时间" width="100" :formatter="formatter"
                            show-overflow-tooltip />
                        <el-table-column prop="status" label="状态" width="90">
                            <template slot-scope="scope">
                                <el-tag type="success" size="small">已录入</el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column prop="action" label="操作" width="170" align="center">
                            <template slot-scope="scope">
                                <!-- 操作按钮 -->
                                <el-button type="primary" size="mini" @click="xiugai(scope.row)">
                                    修改
                                </el-button>
                                <el-button type="danger" size="mini" @click="deleteItem(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="bottom">
                    <el-pagination :current-page="currentPage" background layout="total, prev, pager, next, jumper"
                        :total="totalItems" :page-size="pageSize" @current-change="handleCurrentChange" />
                </div>
            </div>
        </el-main>
        <!-- 页面内容 -->
        <!-- 高级搜索对话框 -->
        <el-dialog title="高级搜索" :visible.sync="visible" width="800px">
            <el-form :model="advancedSearchForm" label-width="120px">
                <el-row>
                    <!-- <el-col :span="12">
                        <el-form-item label="调查时间">
                            <el-date-picker v-model="advancedSearchForm.year" type="year" format="yyyy"
                                value-format="yyyy" placeholder="选择年" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="动物类型：">
                            <el-select v-model="advancedSearchForm.category" placeholder="请选择">
                                <el-option label="全部" value="">
                                </el-option>
                                <el-option v-for="item in list2" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="盟市：">
                            <el-input v-model="advancedSearchForm.mengshi" placeholder="请输入盟市" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="旗县：">
                            <el-input v-model="advancedSearchForm.qixian" placeholder="旗县" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="中文名：">
                            <el-input v-model="advancedSearchForm.name" placeholder="请输入中文名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="学名：">
                            <el-input v-model="advancedSearchForm.ldm" placeholder="请输入学名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="经度：">
                            <el-input v-model="advancedSearchForm.jd" placeholder="请输入经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纬度：">
                            <el-input v-model="advancedSearchForm.wd" placeholder="请输入纬度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="保护等级：">
                            <el-input v-model="advancedSearchForm.protectlevel" placeholder="保护等级" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button type="primary" @click="fetchData(advancedSearchForm)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { MessageBox, Message } from "element-ui";
import * as XLSX from "xlsx";
import { setSessionStorage, clearSessionStorage } from '@/utils/auth'
import { readExcelDwdc } from '@/utils/readNdExcel.js'
export default {
    name: 'AnimalSurvey-management',
    // 组件逻辑
    data() {
        return {
            tableheight: 300,
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的数据量
            totalItems: 0, // 总项目数
            dialogVisible: false,
            isButtonDisabled: false, // 初始化按钮可点击状态
            excelData: null,
            buttonText: "录入全部数据",
            formDataExcel: [],
            errorMessages: [],
            queryForm: {
                name: '',
                category: ''
            },
            tableData: [],
            paginatedData: [],
            filteredData: [],
            delIds: [],
            excelurl: window.location.origin + window.location.pathname + '/动物调查数据.xlsx',
            list2: [
                { label: "哺乳动物", value: "01" },
                { label: "鸟类", value: "02" },
                { label: "鱼类", value: "03" },
                { label: "节肢动物", value: "04" },
            ],
            visible: false,
            advancedSearchForm: {
                year: '',
                name: '',
                category: '',
            }
        };
    },
    computed: {},
    created() {
        console.log('window', window)
        const height = window.innerHeight - 200;
        this.tableheight = height;
        this.fetchData(this.queryForm);
    },
    methods: {
        buildUrl(params) {
            const queryParams = new URLSearchParams(params).toString();
            return `${queryParams}`;
        },
        fetchData(obj) {
            let params = {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                // category: '01',
            }
            const mergeWithFixed = (dynamicObj) =>
                Object.fromEntries(
                    Object.entries({ ...params, ...dynamicObj })
                        .filter(([_, v]) => v != null && v !== '')
                );
            const result = mergeWithFixed(obj);
            console.log(result)
            this.$api.getAnimalSurveyPointsByCondition(this.buildUrl(result)).then((res) => {
                console.log(res)
                let data = res.data.data;
                this.paginatedData = data.list;
                this.totalItems = data.total;
            })
        },
        formatter(row, column) {
            if (row.diaochariqi) {
                const date = new Date(row.diaochariqi);
                const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                return formattedDate;
            } else {
                return ''
            }
        },
        category(row, column) {
            if (row.category1) {
                row.category = this.list2.find(item => item.label === row.category1).value
            }
            return row.category1;
        },
        // 新增
        handleAddPlant() {
            clearSessionStorage();
            console.log("点击了新增按钮");
            this.$router.push({ name: "AnimalSurveyEdit" });
        },
        // 修改
        xiugai(data) {
            console.log("777", data);
            clearSessionStorage();
            setSessionStorage('dwdcParams', JSON.stringify(data))
            // return
            this.$router.push({
                name: "AnimalSurveyEdit",
                params: { id: data.id }
            });
        },

        deleteItem(id) {
            console.log("删除id", id);
            // this.delIds.push(id);
            try {
                MessageBox.confirm("确定要删除吗？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        // 用户点击了确定按钮
                        console.log("用户点击了确定按钮");
                        this.$api
                            .deleteSurveyPoint(id)
                            .then((response) => {
                                // 处理接口返回的数据或其他逻辑

                                // 处理删除成功的情况
                                console.log("删除成功", response.data);
                                Message({
                                    message: "删除成功",
                                    type: "success",
                                });

                                // 在前端移除已删除的项
                                // this.paginatedData = this.tableData.filter(
                                //     (item) => item.id !== id
                                // );
                                // this.totalItems--; // 减少总项目数
                                // this.paginateData(); // 更新分页后的数据
                                this.fetchData(this.queryForm);
                                // this.delIds = [];
                            })
                            .catch((error) => {
                                // 处理失败的情况
                                console.error("失败:", error);
                            });
                    })
                    .catch(() => {
                        // 用户点击了取消按钮
                        console.log("用户点击了取消按钮");
                        this.delIds = [];
                    });
            } catch (error) {
                // 处理删除失败的情况
                console.error("删除失败", error);
            }
        },
        // 录入全部数据
        handleFileUpload(event) {
            this.errorMessages = []; // 清空之前的错误信息
            // 获取上传的Excel文件
            const file = event.target.files[0];
            // 清除输入值以确保即使选择相同的文件，onload 事件仍然会触发
            event.target.value = null;
            // 使用xlsx读取Excel文件
            const reader = new FileReader();

            reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: "array" });
                console.log('work---------', workbook)
                let obj = readExcelDwdc(workbook);
                console.log(obj)
                this.tableData = obj.dwdc;
                return
                // 获取第一个工作表
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];

                // 将Excel数据转为JSON格式
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                if (jsonData.length < 2) {
                    this.errorMessages = ["文件格式错误，至少需要表头行和数据行"];
                    this.isButtonDisabled = true;
                    return;
                }

                // 获取表头
                const headers = jsonData[0];

                // 字段映射关系
                const fieldMapping = {
                    中文名: "wzm",
                    学名: "ldm",
                    实体数量: "shitishuliang",
                    痕迹种类及数量: "henjishuliang",
                    经度: "jd",
                    纬度: "wd",
                    海拔: "hb",
                    坡度: "podu",
                    坡位: "powei",
                    坡向: "poxiang",
                    栖息地类型: "qixi",
                    调查日期: "diaochariqi_temp",
                    发现时间: "faxianshijian_temp",
                    栖息地干扰: "qixiganrao",
                    保护等级: "protectlevel",
                    发现地址: "location",
                    盟市: "mengshi",
                    旗县: "qixian",
                    数据来源: "source",
                    观测者: "guance",
                    照片编号: "zpbh",
                    生境照片编号: "sjzpbh",
                    特征描述: "tezhengmiaoshu",
                    分布多度描述: "fenbuduodumiaoshu",
                };

                // 验证必需字段
                const requiredFields = ["中文名", "学名", "经度", "纬度"];
                const missingFields = requiredFields.filter(
                    (field) => !headers.includes(field)
                );

                if (missingFields.length > 0) {
                    this.errorMessages = [`缺少必需字段: ${missingFields.join(", ")}`];
                    this.isButtonDisabled = true;
                    return;
                }

                const formDataArray = [];
                const errors = [];

                // 解析数据行
                for (let i = 1; i < jsonData.length; i++) {
                    const row = jsonData[i];
                    const rowObject = {};

                    // 映射字段
                    headers.forEach((header, index) => {
                        const fieldName = fieldMapping[header] || header;
                        let value = row[index] || "";

                        // 数据类型转换
                        if (
                            fieldName === "shitishuliang" ||
                            fieldName === "henjishuliang" ||
                            fieldName === "hb" ||
                            fieldName === "podu"
                        ) {
                            value = value ? parseInt(value) || 0 : 0;
                        } else if (fieldName === "jd" || fieldName === "wd") {
                            value = value ? parseFloat(value) || 0 : 0;
                        } else if (
                            fieldName === "diaochariqi_temp" ||
                            fieldName === "faxianshijian_temp"
                        ) {
                            if (value) {
                                const date = new Date(value);
                                value = isNaN(date.getTime()) ? null : date;
                            } else {
                                value = null;
                            }
                        }

                        rowObject[fieldName] = value;
                    });

                    // 合并调查日期和发现时间
                    if (rowObject.diaochariqi_temp || rowObject.faxianshijian_temp) {
                        let combinedDateTime = null;

                        if (rowObject.diaochariqi_temp && rowObject.faxianshijian_temp) {
                            // 如果两个都有，合并日期和时间
                            const surveyDate = new Date(rowObject.diaochariqi_temp);
                            const discoveryTime = new Date(rowObject.faxianshijian_temp);

                            // 创建新的Date对象，使用调查日期的年月日，发现时间的时分秒
                            const combinedDate = new Date(
                                surveyDate.getFullYear(),
                                surveyDate.getMonth(),
                                surveyDate.getDate(),
                                discoveryTime.getHours(),
                                discoveryTime.getMinutes(),
                                discoveryTime.getSeconds()
                            );

                            // 转换为ISO格式字符串
                            combinedDateTime = combinedDate.toISOString();
                        } else if (rowObject.diaochariqi_temp) {
                            // 只有调查日期，转换为ISO格式
                            const date = new Date(rowObject.diaochariqi_temp);
                            combinedDateTime = date.toISOString();
                        } else if (rowObject.faxianshijian_temp) {
                            // 只有发现时间，转换为ISO格式
                            const date = new Date(rowObject.faxianshijian_temp);
                            combinedDateTime = date.toISOString();
                        }

                        rowObject.diaochariqi = combinedDateTime;
                    } else {
                        rowObject.diaochariqi = null;
                    }

                    // 删除临时字段
                    delete rowObject.diaochariqi_temp;
                    delete rowObject.faxianshijian_temp;

                    // 添加动物类别字段
                    rowObject.category = "02"; // 鸟类标识

                    // 验证数据
                    if (!rowObject.wzm || !rowObject.ldm) {
                        errors.push(`第${i + 1}行: 中文名和学名不能为空`);
                        continue;
                    }

                    if (!rowObject.jd || !rowObject.wd) {
                        errors.push(`第${i + 1}行: 经度和纬度不能为空`);
                        continue;
                    }

                    formDataArray.push(rowObject);
                }

                if (errors.length > 0) {
                    this.errorMessages = errors.slice(0, 10); // 只显示前10个错误
                    if (errors.length > 10) {
                        this.errorMessages.push(`...还有${errors.length - 10}个错误`);
                    }
                }

                this.formDataExcel = formDataArray;
                this.isButtonDisabled = formDataArray.length === 0;

                if (formDataArray.length > 0) {
                    this.errorMessages = [];
                    this.buttonText = `录入全部数据 (${formDataArray.length}条)`;
                }

                console.log("解析后的数据:", this.formDataExcel);
            };

            reader.readAsArrayBuffer(file);
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            // this.paginateData();
            this.$nextTick(() => {
                this.fetchData(this.queryForm);
            })
        },
        openExcel() {
            this.$refs.exceluploadinput.click();
        },
        handsubmit() {
            console.log(this.tableData)
            this.$api.batAddSurveyPoint({ surveySampleList: this.tableData }).then((res) => {
                console.log(res)
                if (res.data.code == 0) {
                    Message({
                        message: res.data.data,
                        type: "success",
                    });
                    this.dialogVisible = false;
                    this.fetchData(this.queryForm);
                } else {
                    Message({
                        message: res.data.data,
                        type: "warnig",
                    });
                }
            })
        }
    },
};
</script>

<style scoped>
.el-main {
    color: #333;
    box-sizing: border-box;
}

/* .box {
  padding: 15px;
  background: rgb(255, 255, 255);
  height: 700px;
  position: relative;
  overflow-y: auto;
} */
.top {
    background-color: rgb(232, 232, 232);
    border-radius: 2px;
    padding-left: 20px;
    padding-top: 8px;
    padding-bottom: 7px;
    overflow: hidden;
}

.center {
    /* height: 400px; */
}

.demo-form-inline .el-form-item {
    margin-bottom: 2px;
    vertical-align: top;
    margin-right: 16px;
}

.bottom {
    text-align: right;
}

.file-upload {
    margin-right: 20px;
    /* 调整按钮之间的间距 */
}

.file-upload input {
    display: none;
}

/* 添加样式来美化文件选择按钮 */
.file-upload {
    display: inline-block;
    cursor: pointer;
    padding: 10px 20px;
    background-color: #3498db;
    color: #fff;
    border-radius: 5px;
}

.dialog-content {
    display: flex;
    /* flex-direction: column; */
    /* align-items: center; */
    justify-content: center;
    height: 100%;
}

.batch-btn-row {
    display: flex;
    gap: 16px;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
}

.batch-btn {
    margin: 0 !important;
    min-width: 90px;
}

.file-upload.batch-btn {
    padding: 7px 18px;
    font-size: 14px;
    background-color: #409eff;
    color: #fff;
    border-radius: 4px;
    border: none;
    transition: background 0.2s;
}

.file-upload.batch-btn:hover {
    background-color: #66b1ff;
}

.error-messages {
    background-color: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 4px;
    padding: 10px;
    margin-top: 10px;
}
</style>
<style>
.excel-dialo .el-dialog__footer {
    border-top: 1px solid #DCDFE6;
    padding-bottom: 10px;
    display: flex;
    justify-content: space-between;
}
</style>
